package com.example.a0521.fragments;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.a0521.R;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AlbumDetailFragment extends Fragment {
    OkHttpClient client=new OkHttpClient();
    public AlbumDetailFragment() {
        super(R.layout.fragment_album_detail);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle=getArguments();
        int id=bundle.getInt("id");
        ImageView imageView=view.findViewById(R.id.img);
        Request request=new Request.Builder()
                .url("http://johnyu.cn:3000/albums"+id)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
            AlbumDetailFragment.this.getActivity()
                    .runOnUiThread(()->{
                        try{
                            RequestOptions options=new RequestOptions();
                            options.circleCrop();
                            String body=response.body().string();
                            JSONObject obj=new JSONObject(body);
                            String imgUrl=obj.getString("img");
                            Glide.with(AlbumDetailFragment.this).load(imgUrl)
                                    .apply(options)
                                    .into(imageView);
                        }catch (Exception e){
                            e.printStackTrace();
                        }


                    });


            }
        });

    }
}
